package com.example.controller;

import com.example.domain.po.Orders;
import com.example.domain.vo.OrderVo;
import com.example.service.OrdersService;
import com.example.util.PageBean;
import com.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @GetMapping("/list")
    public PageBean<OrderVo> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "2") Integer pageSize,
            Integer status,
            String startTime,
            String endTime,
            Integer userId
    ) {
        return ordersService.list(pageNum, pageSize, status, startTime, endTime, userId);
    }


    @GetMapping("/cancel")
    public Result<String> cancelOrdersById(Integer id) {
        Orders order = ordersService.findById(id);
         ordersService.cancelOrder(order);
         return Result.success("取消成功");
    }

    /**
     * 查询用户是否购买过此课程
     * @return
     */
    @GetMapping("/getByUidAndCid")
    public Result<Orders> getByUidAndCid(Integer cid, Integer uid){
        System.out.println(cid);
        return Result.success(ordersService.getByUidAndCid(cid,uid));
    }

    /**
     * 生成订单
     * @return
     */
    @PostMapping("/add")
    public Result<Long> add(@RequestBody Orders orders){
        System.out.println("111111111"+orders);
        return Result.success(ordersService.add(orders));
    }


    @Scheduled(fixedRate = 1000 * 60 * 10)

    public void cancelOrders() {
        // 查询所有未支付且超过10分钟的订单
        List<Orders> orders = ordersService.findUnpaidOrdersOver30Minutes();
        for (Orders order : orders) {
            ordersService.cancelOrder(order);
        }
    }


}
